﻿using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using Aij1.Utils;

namespace Aij1.Model
{
    public static class XpoHelper
    {
        public static Session GetNewSession()
        {
            return new Session(DataLayer);
        }

        public static UnitOfWork GetNewUnitOfWork()
        {
            return new UnitOfWork(DataLayer);
        }

        private readonly static object lockObject = new object();

        static volatile IDataLayer fDataLayer;
        static IDataLayer DataLayer
        {
            get
            {
                if (fDataLayer == null)
                {
                    lock (lockObject)
                    {
                        if (fDataLayer == null)
                        {
                            fDataLayer = GetDataLayer();
                        }
                    }
                }
                return fDataLayer;
            }
        }

        private static IDataLayer GetDataLayer()
        {
            // Code that runs on the application startup 
            // Specify the connection string, which is used to open a database.  
            // It's supposed that you've already created the Comments database within the App_Data folder. 
            string conn = ConfigurationManager.ConnectionStrings["DefaultConnStr"].ConnectionString;
            DevExpress.Xpo.Metadata.XPDictionary dict = new DevExpress.Xpo.Metadata.ReflectionDictionary();
            // Initialize the XPO dictionary. 
            dict.GetDataStoreSchema(typeof(A_Article).Assembly);
            DevExpress.Xpo.XpoDefault.Session = null;
            DbConnection connection = DBHelper.Comm.CreateConnection();
            DevExpress.Xpo.DB.IDataStore store =
            DevExpress.Xpo.XpoDefault.GetConnectionProvider(connection, DevExpress.Xpo.DB.AutoCreateOption.DatabaseAndSchema);
            return new DevExpress.Xpo.ThreadSafeDataLayer(dict, store);
        }
    }
}